package vip.xiaonuo.biz.modular.fzrole.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.fzrole.param.*;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.fzrole.entity.BizFzRole;
import vip.xiaonuo.biz.modular.fzrole.mapper.BizFzRoleMapper;
import vip.xiaonuo.biz.modular.fzrole.service.BizFzRoleService;

import java.util.List;

/**
 * 分销人角色表Service接口实现类
 *
 * @author xiao
 *
 **/
@Service
public class BizFzRoleServiceImpl extends ServiceImpl<BizFzRoleMapper, BizFzRole> implements BizFzRoleService {
    @Autowired
    private WxMaService wxMaService;

    @Override
    public Page<BizFzRole> page(BizFzRolePageParam bizFzRolePageParam) {
        QueryWrapper<BizFzRole> queryWrapper = new QueryWrapper<>();
        // 查询条件
        // 角色名称
        if(ObjectUtil.isNotEmpty(bizFzRolePageParam.getRoleName())) {
            queryWrapper.lambda().like(BizFzRole::getRoleName, bizFzRolePageParam.getRoleName());
        }
        // 分账角色
        if(ObjectUtil.isNotEmpty(bizFzRolePageParam.getRoleValue())) {
            queryWrapper.lambda().eq(BizFzRole::getRoleValue, bizFzRolePageParam.getRoleValue());
        }
        // 上级id
        if(ObjectUtil.isNotEmpty(bizFzRolePageParam.getParentId())) {
            queryWrapper.lambda().eq(BizFzRole::getParentId, bizFzRolePageParam.getParentId());
        }
        // 分账类型
        if(ObjectUtil.isNotEmpty(bizFzRolePageParam.getFzType())) {
            queryWrapper.lambda().eq(BizFzRole::getFzType, bizFzRolePageParam.getFzType());
        }
        // 关键词查询
        String searchKey = bizFzRolePageParam.getSearchKey();
        if(ObjectUtil.isNotEmpty(searchKey)) {
            queryWrapper.lambda().like(BizFzRole::getRoleName, searchKey);
        }
        // 排序
        if(ObjectUtil.isAllNotEmpty(bizFzRolePageParam.getSortField(), bizFzRolePageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizFzRolePageParam.getSortOrder());
            queryWrapper.orderBy(true, bizFzRolePageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizFzRolePageParam.getSortField()));
        } else {
            // 默认排序
            queryWrapper.lambda().orderByAsc(BizFzRole::getRoleName);
        }
        // 分页查询
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizFzRoleAddParam bizFzRoleAddParam) {
        // 参数转换为实体
        BizFzRole bizFzRole = BeanUtil.toBean(bizFzRoleAddParam, BizFzRole.class);
        this.save(bizFzRole);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizFzRoleEditParam bizFzRoleEditParam) {
        // 获取分销人角色表
        BizFzRole bizFzRole = this.queryEntity(bizFzRoleEditParam.getId());
        // 请求参数转化为实体
        BeanUtil.copyProperties(bizFzRoleEditParam, bizFzRole);
        this.updateById(bizFzRole);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizFzRoleIdParam> bizFzRoleIdParamList) {
        // 获取所有ID
        List<String> bizFzRoleIdList = CollStreamUtil.toList(bizFzRoleIdParamList, BizFzRoleIdParam::getId);
        // 批量删除
        this.removeByIds(bizFzRoleIdList);
    }

    @Override
    public BizFzRole detail(BizFzRoleIdParam bizFzRoleIdParam) {
        return this.queryEntity(bizFzRoleIdParam.getId());
    }

    @Override
    public BizFzRole queryEntity(String id) {
        // 获取分销人角色
        BizFzRole bizFzRole = this.getById(id);
        if(ObjectUtil.isEmpty(bizFzRole)) {
            throw new CommonException("分销人角色不存在，id值为：{}", id);
        }
        return bizFzRole;
    }

    @Override
    public List<BizFzRole> querySubRoles(String roleValue) {
        // 先查找当前角色
        QueryWrapper<BizFzRole> currentRoleWrapper = new QueryWrapper<>();
        currentRoleWrapper.lambda().eq(BizFzRole::getRoleValue, roleValue);
        BizFzRole currentRole = this.getOne(currentRoleWrapper);

        if (currentRole == null) {
            return Lists.newArrayList(); // 返回空列表表示不存在
        }

        // 查找下级角色
        QueryWrapper<BizFzRole> subRoleWrapper = new QueryWrapper<>();
        subRoleWrapper.lambda().eq(BizFzRole::getParentId, currentRole.getId());

        return this.list(subRoleWrapper);
    }

    @Override
    public String generateMaQrCode(WxQrCodeParam wxQrCodeParam) {
        try {
            // 设置默认值
            String scene = StrUtil.isBlank(wxQrCodeParam.getScene()) ? "a=1" : wxQrCodeParam.getScene();
            String page = StrUtil.isBlank(wxQrCodeParam.getPage()) ? "pages/index/index" : wxQrCodeParam.getPage();
            boolean checkPath = wxQrCodeParam.getCheckPath() == null ? true : wxQrCodeParam.getCheckPath();
            String envVersion = StrUtil.isBlank(wxQrCodeParam.getEnvVersion()) ? "release" : wxQrCodeParam.getEnvVersion();
            int width = wxQrCodeParam.getWidth() == null ? 430 : wxQrCodeParam.getWidth();
            boolean autoColor = wxQrCodeParam.getAutoColor() == null ? false : wxQrCodeParam.getAutoColor();
            boolean isHyaline = wxQrCodeParam.getIsHyaline() == null ? false : wxQrCodeParam.getIsHyaline();

            // 根据实际方法签名调整参数顺序:
            // createWxaCodeUnlimitBytes(String var1, String var2, boolean var3, String var4, int var5, boolean var6, WxMaCodeLineColor var7, boolean var8)
            // 推测参数对应关系:
            // var1=scene, var2=page, var3=checkPath, var4=envVersion, var5=width, var6=autoColor, var7=lineColor, var8=isHyaline
            byte[] qrCodeBytes = wxMaService.getQrcodeService().createWxaCodeUnlimitBytes(
                    scene,      // 场景值
                    page,       // 页面路径
                    checkPath,  // 是否检查页面路径
                    envVersion, // 环境版本
                    width,      // 宽度
                    autoColor,  // 自动配置线条颜色
                    null,       // 线条颜色配置(null使用默认值)
                    isHyaline   // 是否需要透明底色
            );

            // 将字节数组转为Base64字符串
            String base64QrCode = cn.hutool.core.codec.Base64.encode(qrCodeBytes);

            // 添加Data URI前缀，便于直接在前端使用
            return "data:image/png;base64," + base64QrCode;

        } catch (WxErrorException e) {
            log.error("生成小程序码失败", e);
            throw new CommonException("生成小程序码失败: " + e.getMessage());
        }
    }
}
